package com.kvc.extend.papervision3d 
{
	import gs.easing.*;
	import gs.TweenMax;

	import com.as3dmod.ModifierStack;
	import com.as3dmod.modifiers.Bend;
	import com.as3dmod.plugins.pv3d.LibraryPv3d;
	import com.as3dmod.util.ModConstant;

	import org.papervision3d.core.proto.MaterialObject3D;
	import org.papervision3d.objects.DisplayObject3D;
	import org.papervision3d.objects.primitives.Plane;

	import flash.events.Event;
	/**
	 * @author Kevin Cao
	 */
	public class Page3D extends DisplayObject3D 
	{
		public static const LIB : LibraryPv3d = new LibraryPv3d();
		public static const EASE : Function = Quad.easeOut;

		private var pageID : int;

		private var plane : Plane;

		private var mstack : ModifierStack;
		private var bend : Bend;

		public function Page3D(id : int, mat1 : MaterialObject3D, mat2 : MaterialObject3D, width : Number = 600, height : Number = 800) 
		{
			pageID = id;
			name = "page" + pageID;
			
			material = new DoubleSidedMaterial(mat1, mat2);
			
			plane = new Plane(material, width, height, Book3D.SEGMENTS_W, Book3D.SEGMENTS_H);
			plane.x = width / 2;
			plane.z = id * 0.01;
			plane.useOwnContainer = true;
			addChild(plane);

			mstack = new ModifierStack(LIB, plane);
			bend = new Bend(0, 0.3, -Math.PI * 0.55);
			bend.constraint = ModConstant.LEFT;
			mstack.addModifier(bend);
		}

		public function pageUp() : void 
		{
			z = -0.01;
			if(TweenMax.isTweening(bend)) 
			{
				TweenMax.to(bend, Book3D.TIME, {force: 0, ease: EASE, onUpdate: updateHandler, onComplete: completeHandler});			} else {
				TweenMax.to(bend, Book3D.TIME, {force: 0, bezierThrough: [{force: -0.8}], ease: EASE, onUpdate: updateHandler, onComplete: completeHandler});
			}
			TweenMax.to(this, Book3D.TIME, {rotationY: 0, ease: EASE});
		}

		public function pageDown() : void 
		{
			z = -0.01;
			if(TweenMax.isTweening(bend)) 
			{				TweenMax.to(bend, Book3D.TIME, {force: 0, ease: EASE, onUpdate: updateHandler, onComplete: completeHandler});
			} else {
				TweenMax.to(bend, Book3D.TIME, {force: 0, bezierThrough: [{force : 0.8}], ease: EASE, onUpdate: updateHandler, onComplete: completeHandler});
			}
			TweenMax.to(this, Book3D.TIME, {rotationY: 180});
		}

		private function updateHandler() : void 
		{
			mstack.apply();
		}

		private function completeHandler() : void 
		{
			z = 0;
			dispatchEvent(new Event(Event.COMPLETE));
		}
	}
}
